/*


 */

package jas.http.response;

/**
 *
 *
 */
public class HttpResponseFormatter {
    
    public static HttpResponse parseResponse(String str) throws IllegalArgumentException {
        if (str == null)
            throw new IllegalArgumentException("Message is null.");
        if (str.length() == 0)
            throw new IllegalArgumentException("Cannot parse empty HTTP response.");
        
        HttpResponse response = new HttpResponse();
        
        int splitAt = str.indexOf("\r\n\r\n");
        
        if (splitAt == -1)
            splitAt = str.length();
        
        String header = str.substring(0, splitAt);
        String body = "";
        if (splitAt < str.length()) {
            body = str.substring(splitAt + "\r\n\r\n".length());
        }
        
        String[] headerLines = header.split("\r\n");
        
        String responseLine = headerLines[0];
        String[] responseLineParts = responseLine.split(" ");
        
        if (responseLineParts.length < 3)
            throw new IllegalArgumentException("Incomplete response line: " + responseLine);
        
        int code = Integer.valueOf(responseLineParts[1]);
        response.setCode(ResponseCode.fromNumber(code));
        
        response.setBody(new StringResponseBody(body));
        
        return response;
    }
    
}
